package com.home.zqt.platform.dao;

import com.home.zqt.platform.common.EnvHelper;
import com.home.zqt.platform.domain.MJEnvironmentEnum;
import com.home.zqt.platform.domain.MJMenu;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author soon
 */
@Service
public class MenuDao {

    @Autowired
    @Qualifier("sqlManagerProduct")
    private SQLManager sqlManagerProduct;
    @Autowired
    @Qualifier("sqlManagerPrepare")
    private SQLManager sqlManagerPrepare;
    @Autowired
    @Qualifier("sqlManagerDaily")
    private SQLManager sqlManagerDaily;

    public long findMaxId(MJEnvironmentEnum env) {
        MJMenu menu = null;
        switch (env) {
            case PRODUCT:
                return sqlManagerProduct.selectSingle("menu.findMaxId", null, Integer.class);
            case PREPARE:
                return sqlManagerPrepare.selectSingle("menu.findMaxId", null, Integer.class);
            case DAILY:
                return sqlManagerDaily.selectSingle("menu.findMaxId", null, Integer.class);
            default:
                return 0;
        }
    }

    public MJMenu findById(Long id) {
        return sqlManagerProduct.single(MJMenu.class, id);
    }

    public List<MJMenu> findAll() {
        return sqlManagerProduct.select("menu.findAll", MJMenu.class);
    }

    public List<MJMenu> findRootList() {
        return sqlManagerProduct.select("menu.findRootList", MJMenu.class);
    }

    public List<MJMenu> findChildrenList(MJMenu condition) {
        return sqlManagerProduct.select("menu.findChildrenList", MJMenu.class, condition);
    }

    public void create(List<MJEnvironmentEnum> envList, MJMenu menu) throws Exception {
        long idProduct = 0;
        long idPrepare = 0;
        long idDaily = 0;
        if (EnvHelper.isProduct(envList)) {
            idProduct = this.findMaxId(MJEnvironmentEnum.PRODUCT);
        }
        if (EnvHelper.isPrepare(envList)) {
            idPrepare = this.findMaxId(MJEnvironmentEnum.PREPARE);
        }
        if (EnvHelper.isDaily(envList)) {
            idDaily = this.findMaxId(MJEnvironmentEnum.DAILY);
        }

        long maxId = Math.max(idProduct, Math.max(idPrepare, idDaily));

        menu.setId(maxId);
        sqlManagerProduct.insert(menu, true);
    }
}
